<?php

namespace App\Http\Controllers\Api;

use AlibabaCloud\Client\AlibabaCloud;
use App\Http\Util\Lib\StoreForget;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\StaffModel;
use App\Models\OrderModel;
use App\Models\OrderInfoModel;
use Illuminate\Support\Facades\Validator;
use phpDocumentor\Reflection\DocBlock\Tags\Return_;
use Intervention\Image\Facades\Image;
class OrderController extends Controller
{
    /**
     * 中间件
     */
    public function __construct(){
        $this -> middleware('login_check')->except(['order_info']);
    }

    /**
     * 下訂單
     */
    public function addOrder(Request $request,StaffModel $staffModel,OrderModel $orderModel,OrderInfoModel $orderInfoModel){
        try{
            // 验证规则
            $rule = [
                'sender_province' => 'required',
                'sender_city' => 'required',
                'sender_district' => 'required',
                'sender_address' => 'required',
                'sender_name' => 'required',
                'sender_phone' => 'required',
                'consignee_province' => 'required',
                'consignee_city' => 'required',
                'consignee_district' => 'required',
                'consignee_address' => 'required',
                'consignee_name' => 'required',
                'consignee_phone' => 'required',
                'goods_data' => 'required|array',
                "goods_data.*"  => "required",
                "is_collection" =>'required',
                "is_sender"=>'required',
                //"goods_money"=>'required',
                "sender_money"=>'required',
               // "pay_type"=>'required',
                //"goods_img_one"=>'required',
                //"goods_img_two"=>'required',
                //"order_remarks"=>'required',
            ];

            // 验证信息
            $message = [
                'sender_province.required' => '寄件人省份不能为空',
                'sender_city.required' => '寄件人城市不能为空',
                'sender_district.required' => '寄件人区不能为空',
                'sender_address.required' => '寄件人街道门牌不能为空',
                'sender_name.required' => '寄件人姓名不能为空',
                'sender_phone.required' => '寄件人电话不能为空',
                'consignee_province.required' => '收件人省份不能为空',
                'consignee_city.required' => '收件人城市不能为空',
                'consignee_district.required' => '收件人地区不能为空',
                'consignee_address.required' => '收件人街道门牌不能为空',
                'consignee_name.required' => '收件人姓名不能为空',
                'consignee_phone.required' => '收件人电话不能为空',
                'goods_data.required' => 'goods_data货品必传',
                'goods_data.array' => 'goods_data为数组',
                'is_collection.required'=>'必填是否代收货款',
                'is_sender.required'=>'必填是否代到付快递费',
               // 'goods_money.required'=>'货款不能为空',
                'sender_money.required'=>'快递费不能为空',
                //'pay_type.required'=>'支付方式不能为空',
                //'goods_img_one.required'=>'商品图片1必传',
                //'goods_img_two.required'=>'商品图片2必传',
                //'order_remarks'=>'支付',
            ];
           /* $validator = Validator::make($request->all(),[
                'photos.profile' => 'required|image',//验证数组中的某个key的值
            ]);*/
            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            //检查是否已发车
            $st_mileage = Db::table('today_mileage')
                ->where('staff_id',auth('api') -> user() -> id)
                ->whereDate('created_at',date('Y-m-d'))
                ->first();

            if(!$st_mileage){
                throw new \Exception('没有发车记录');
            }

            $orderModel->staff_id = auth('api') -> user() -> id;
            $orderModel->admin_id = auth('api') -> user() -> admin_id;
            $orderModel->car_license = auth('api') -> user() -> car_license;
            $orderModel->order_number = order_number();
            $orderModel->sender_province = $request->input('sender_province');
            $orderModel->sender_city = $request->input('sender_city');
            $orderModel->sender_district = $request->input('sender_district');
            $orderModel->sender_address = $request->input('sender_address');
            $orderModel->sender_name = $request->input('sender_name');
            $orderModel->sender_phone = $request->input('sender_phone');
            $orderModel->consignee_province = $request->input('consignee_province');
            $orderModel->consignee_city = $request->input('consignee_city');
            $orderModel->consignee_district = $request->input('consignee_district');
            $orderModel->consignee_address = $request->input('consignee_address');
            $orderModel->consignee_name = $request->input('consignee_name');
            $orderModel->consignee_phone = $request->input('consignee_phone');
            $orderModel->goods_remarks = $request->input('goods_remarks')?$request->input('goods_remarks'):'';
            $orderModel->order_remarks = $request->input('order_remarks')?$request->input('order_remarks'):'';

            $orderModel->is_sender = $request->input('is_sender');
            $orderModel->is_collection = $request->input('is_collection');

            $orderModel->sender_money = $request->input('sender_money');
            //$orderModel->goods_money = $request->input('goods_money');

            $orderModel->goods_img = empty($request->input('goods_img'))?'':$request->input('goods_img');
            //$orderModel->goods_img_two = $request->input('goods_img_two');
            date_default_timezone_set("PRC");

            //计算寄件人付款
            $sign_sender_money = 0;
            if ($request->input('is_sender')==1){

                $sign['order_id'] = $orderModel->id;
                $sign_sender_money = $request->input('sender_money');
                $sign['sign_pay_status'] = 1;

            }elseif ($request->input('is_sender')==2){

                $orderModel->pay_type = $request->input('pay_type');

                if(empty($request->input('pay_type'))){
                    throw new \Exception('支付方式pay_type必传');
                }

                if($request->input('pay_type')==2){
                    $orderModel->pay_status = 3;
                }elseif($request->input('pay_type')==3){
                    $orderModel->pay_status = 2;
                }

                $sender_money = $request->input('sender_money');
                $orderModel->sender_pay_money = $sender_money;

            }

            $orderModel->order_status = 1;

            $res = $orderModel->save();
            if(!$res){
                throw new \Exception('订单添加失败');
            }

            //计算签收人付款
            //是否到付快递费
            $sign['order_id'] = $orderModel->id;

            //是否代收付货款
            $sign_goods_money = 0;
            if($request->input('is_collection')==1){
                if(empty($request->input('goods_money'))){
                    throw new \Exception('goods_money必传');
                }
                $orderModel->goods_money = $request->input('goods_money');
                $sign_goods_money = $request->input('goods_money');
            }

            $sign['sign_pay_money'] = $sign_sender_money + $sign_goods_money;

            $re = Db::table('sign')->insert($sign);

            if(!$re){
                throw new \Exception('sign插入失败');
            }

            $orderModel->save();

            $goods_data = $request->input('goods_data');
            $total_goods_number = 0;

            // 添加详情
            foreach ($goods_data as $k => $v){

                if(empty($v['goods_number'])){
                    throw new \Exception('goods_number不能为空');
                }

                if(empty($v['goods_name'])){
                    throw new \Exception('goods_name不能为空');
                }

                if(empty($v['goods_unit'])){
                    throw new \Exception('goods_unit不能为空');
                }

                $temp['order_id'] =$orderModel->id;
                $total_goods_number +=$v['goods_number'];
                $temp['goods_name'] =$v['goods_name'];
                $temp['goods_number'] =$v['goods_number'];
                $temp['goods_unit'] = $v['goods_unit'];
                $temp['created_at']= date("Y-m-d h:i:s");

                $orderModel -> order_info() -> create($temp);
            }

            $orderModel->total_goods_number = $total_goods_number;

            $orderModel->save();

            return response() -> json([
                'error_code' => 0,
                'msg' => '提交成功'
            ]);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }



    /**
     *订单列表
     */
    public function order_list(Request $request,OrderModel $orderModel,OrderInfoModel $orderInfoModel){

        $staff_id = auth('api') -> user() -> id;

        if(!empty($request->input('order_status'))){
            $where['order_status'] = $request->input('order_status');
        }else{
            $where =[];
        }

        if(!empty($request->input('consignee_name'))){
            $where2['consignee_name'] = $request->input('consignee_name');
        }else{
            $where2 =[];
        }

        $orderlist = $orderModel
            ->where('staff_id',$staff_id)
            ->where($where)
            ->where($where2)
            ->orderBy('created_at','desc')
            ->orderBy('updated_at','desc')
            ->paginate(15);

        return response() -> json([
            'error_code' => 0,
            'msg' => '提交成功',
            'data' =>$orderlist
        ]);

    }


    /**
     *订单详情
     */
    public function order_info(Request $request,OrderModel $orderModel,OrderInfoModel $orderInfoModel){
        //var_dump(auth('api') -> user() -> staff_name);die;
        $order_number = $request->input('order_number');
        if(empty($order_number)){
            $order = $orderModel->where('id',$request->input('order_id'))->first();
        }else{
            $order = $orderModel->where('order_number',$request->input('order_number'))->first();
        }

       // var_dump($order);die;
        //$staff_id = auth('api') -> user() -> id;
        date_default_timezone_set("PRC");
        if(empty($order)){
            return response() -> json([
                'error_code' => 400,
                'msg' => '订单不存在'
            ]);
        }

        if(!empty($order->order_number)){
            $goods_array = explode(',',$order->goods_img);
            //var_dump($goods_array);die;
            $order = $order->toArray();
            foreach ($goods_array as $k=>$v){
                $goods_img_img = Db::table('images')->where('id',$v)->value('url');
                //var_dump($goods_img_img);die;
                if(empty($goods_img_img)){
                    $order['goods_img_array'][$k] ='';
                }else{

                    $order['goods_img_array'][$k] = getDomain().'/'.$goods_img_img;
                }
            }
        }


        $order['goods_data'] = $orderInfoModel->where('order_id',$request->input('order_id'))->get();

        $order['sign'] = Db::table('sign')->where('order_id',$request->input('order_id'))->get();
        if(count($order['sign'])>0){

            foreach ($order['sign'] as $k=>$v){

                $url2 = Db::table('images')->where('id',$v->record_mid)->value('url');
                if(!empty($url)){
                    $order['sign'][$k]->sign_img = getDomain().'/'.$url2;
                }else{
                    $order['sign'][$k]->sign_img ='';
                }

            }

        }



        $order['staff_name'] = auth('api') -> user() -> staff_name;

        return response() -> json([
            'error_code' => 0,
            'msg' => '提交成功',
            'data' =>$order
        ]);
    }


    /**
     * 签收
     */
    public function Sign(Request $request,OrderModel $orderModel){
       // auth('api') -> user() -> id;
        try{

            // 验证规则
            $rule = [
                'sign_mid' => 'required',
                'order_id' => 'required',
                'sign_adress' => 'required',
                //'sign_img_array' => 'required',
                //'sign_postage_type' => 'required',
                //'sign_goods_type' => 'required',
                //'sign_type' => 'required',
            ];

            // 验证信息
            $message = [
                'sign_mid.required' => '图片id不能为空',
                'order_id.required' => '订单ID不能为空',
                'sign_adress.required' => '地址不能为空',
                //'sign_img_array.required' => '地址不能为空',
                //'sign_postage_type.required' => '签收邮费方式不能为空',
               // 'sign_goods_type.required' => '签收货款方式不能为空',
                //'sign_type.required' => '签收位置不能为空',
            ];


            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            date_default_timezone_set("PRC");
            $sign_postage_type = $request->input('sign_postage_type');
            $sign_goods_type = $request->input('sign_goods_type');

            $order =$orderModel->where('id',$request->input('order_id'))->first();
            if(empty($order)){
                throw new \Exception('订单不存在');
            }

            if($order->order_status==2){
                throw new \Exception('订单签收过');
            }

            if($order->is_sender==1){
                if(empty($sign_postage_type)){
                    throw new \Exception('必须选择邮费到付收款方式');
                }

            }

            if($order->is_collection==1){
                if(empty($sign_goods_type)){
                    throw new \Exception('必须选择货款收款方式');
                }

            }

/*            $res = Db::table('sign_record')
                ->where('order_id',$request->input('order_id'))
                ->update(['sign_mid'=>$request->input('sign_mid'),'sign_status'=>1,'updated_at'=>date("Y-m-d h:i:s")]);*/

            $res = Db::table('sign_record')
                ->insert(['order_id'=>$request->input('order_id'),'sign_mid'=>$request->input('sign_mid'),'sign_status'=>1,'created_at'=>date("Y-m-d h:i:s")]);

            if(!$res){
                throw new \Exception('签收记录更新失败');
            }

            $re = Db::table('sign')
                ->where('order_id',$request->input('order_id'))
                ->update([
                    'sign_mid'=>$request->input('sign_mid'),
                    'sign_status'=>1,
                    'sign_postage_type'=>$sign_postage_type,
                    'sign_goods_type'=>$sign_goods_type,
                    'sign_adress'=>$request->input('sign_adress'),
                    'sign_goods_img'=>$request->input('sign_goods_img'),
                    'updated_at'=>date("Y-m-d h:i:s")]);

            if(!$re){
                throw new \Exception('签收更新失败');
            }

            //$orderModel->id = $request->input('order_id');

            $order->order_status = 2;
            $order->updated_at = date("Y-m-d h:i:s");
            $re = $order->save();

            if(!$re){
                throw new \Exception('订单记录更新失败');
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '保存成功',
            ]);


        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }
    }


    /**
     * 签收异常
     */
    public function sign_abnormal(Request $request,OrderModel $orderModel){
        try{
            // 验证规则
            $rule = [
                'record_mid' => 'required',
                'remarks' => 'required',
                'order_id' => 'required',
                //'sign_type' => 'required',
            ];

            // 验证信息
            $message = [
                'record_mid.required' => '图片id不能为空',
                'remarks.required' => '签收异常原因不能为空',
                'order_id.required' => '订单ID不能为空',
                //'sign_type.required' => '签收位置不能为空',
            ];
            date_default_timezone_set("PRC");
            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $order =$orderModel->where('id',$request->input('order_id'))->first();
            if(empty($order)){
                throw new \Exception('订单不存在');
            }

            if($order->order_status==2){
                throw new \Exception('订单已签收完成');
            }

            if($order->order_status==3){
                throw new \Exception('订单已记录过签收异常');
            }


                $res = Db::table('sign_record')
                ->insert(['order_id'=>$request->input('order_id'),'record_mid'=>$request->input('record_mid'),'sign_status'=>2,'created_at'=>date("Y-m-d h:i:s"),'sign_info'=>$request->input('remarks')]);

            if(!$res){
                throw new \Exception('签收记录更新失败');
            }

            $re = Db::table('sign')
                ->where('order_id',$request->input('order_id'))
                ->update(['record_mid'=>$request->input('record_mid'),'sign_status'=>2,'updated_at'=>date("Y-m-d h:i:s"),'sign_info'=>$request->input('remarks')]);

            if(!$re){
                throw new \Exception('签收更新失败');
            }

            $order->order_status = 3;
            $order->updated_at = date("Y-m-d h:i:s");
            $re = $order->save();

            if(!$re){
                throw new \Exception('订单记录更新失败');
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '保存成功',
            ]);


        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }
    }


    /**
     * 再次派送
     */
    public function again_deliver(Request $request,OrderModel $orderModel){
        try{
            // 验证规则
            $rule = [
               // 'record_mid' => 'required',
                'order_id' => 'required',
            ];

            // 验证信息
            $message = [
                //'record_mid.required' => '图片id不能为空',
                'order_id.required' => '订单ID不能为空',
            ];
            date_default_timezone_set("PRC");
            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $order =$orderModel->where('id',$request->input('order_id'))->first();
            if(empty($order)){
                throw new \Exception('订单不存在');
            }

            if($order->order_status!=3){
                throw new \Exception('订单不在异常签收状态');
            }

            //auth('api') -> user();
            $order->order_status = 1;
            $res = $order->save();
            if(!$res){
                throw new \Exception('订单状态更新失败');
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '保存成功',
            ]);


        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }
    }


    /**
     * 上传图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function up_img(Request $request){

        try{

            // 验证规则
            $rule = [
                'photo' => 'required',

            ];

            // 验证信息
            $message = [
                'photo.required' => '图片文件不能为空',

            ];

            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $img = $request->file('photo');
            date_default_timezone_set("PRC");

            // 获取文件后缀名
            $suffix = $img->getClientOriginalExtension();

            // 定义保存的路径
            $avatarUrl = 'uploads/images/'. date('Ymd');

            // 验证文件夹是否存在
            if(!is_dir($avatarUrl)){
                // 不存在则创建
                mkdir($avatarUrl,0777,true);
            }

            // 获取图片名称
            $imagesName = md5(time()). '.' . $suffix;

            $old_avatarUrl = $avatarUrl.'/' . $imagesName;

            $img = Image::make($request->file('photo'))->save($old_avatarUrl);

            if(!is_file($old_avatarUrl)){
                return response() -> json([
                    'error_code' => 400,
                    'msg' => '上传文件保存失败'
                ]);
            }


            $mid = Db::table('images')->insertGetId(['url'=>$old_avatarUrl]);
            if(empty($mid)){
                return response() -> json([
                    'error_code' => 400,
                    'msg' => '图片url更新失败'
                ]);
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '保存成功',
                'data'=>[
                    'mid'=>$mid
                ]
            ]);


        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }

    //关联客户信息
    public function relation_customer(Request $request){
        $word = $request->input('word');
        $data = Db::table('order')
            ->where('sender_name', 'like', '%' . $word. '%')
            ->select(['sender_phone','sender_address','sender_district','sender_city','sender_name','sender_province'])
            ->distinct (['sender_phone','sender_address','sender_district','sender_city','sender_name','sender_province'])
                ->get();


        return response() -> json([
            'error_code' => 0,
           // 'msg' => '保存成功',
            'data'=>$data
        ]);
    }

    //关联客户信息
    public function phone_customer(Request $request){
        $word = $request->input('word');
        $data = Db::table('order')
            ->where('sender_phone', 'like', '%' . $word. '%')
            ->select(['sender_phone','sender_address','sender_district','sender_city','sender_name','sender_province'])
            ->distinct (['sender_phone','sender_address','sender_district','sender_city','sender_name','sender_province'])
            ->get();


        return response() -> json([
            'error_code' => 0,
            // 'msg' => '保存成功',
            'data'=>$data
        ]);
    }


    //关联收件客户信息
    public function relation_consignee(Request $request){
        $word = $request->input('word');
        $data = Db::table('order')
            ->where('consignee_name', 'like', '%' . $word. '%')
            ->select(['consignee_phone','consignee_address','consignee_district','consignee_city','consignee_name','consignee_province'])
            ->distinct (['consignee_phone','consignee_address','consignee_district','consignee_city','consignee_name','consignee_province'])
            ->get();


        return response() -> json([
            'error_code' => 0,
            // 'msg' => '保存成功',
            'data'=>$data
        ]);
    }

    //关联收件客户信息
    public function phone_consignee(Request $request){
        $word = $request->input('word');
        $data = Db::table('order')
            ->where('consignee_phone', 'like', '%' . $word. '%')
            ->select(['consignee_phone','consignee_address','consignee_district','consignee_city','consignee_name','consignee_province'])
            ->distinct (['consignee_phone','consignee_address','consignee_district','consignee_city','consignee_name','consignee_province'])
            ->get();

        return response() -> json([
            'error_code' => 0,
            // 'msg' => '保存成功',
            'data'=>$data
        ]);
    }


    //订单作废
    public function void_order(Request $request,OrderModel $orderModel){
        $order_id = $request->input('order_id');
        $order = $orderModel
            ->where('id',$order_id)
            ->where('staff_id',auth('api') -> user()->id)
            ->first();
        if(empty($order)){
            return response() -> json([
                'error_code' => 400,
                'msg' => '订单不存在'
                //'data'=>$data
            ]);
        }

        $order->order_status = 5;
        $res = $order->save();
        if(!$res){
            return response() -> json([
                'error_code' => 400,
                'msg' => '更新失败'
            ]);
        }

        return response() -> json([
            'error_code' => 0,
            'msg' => '更新成功'
        ]);

    }



}
